package com.qingchi.server.controller;

import com.oracle.truffle.js.scriptengine.GraalJSScriptEngine;
import org.graalvm.polyglot.Context;
import org.graalvm.polyglot.HostAccess;
import org.graalvm.polyglot.Source;
import org.graalvm.polyglot.Value;
import org.springframework.util.ResourceUtils;

import javax.script.Bindings;
import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Map;

public class TestGraaljs {

    public static void main(String[] args) throws ScriptException, IOException {

        /*ScriptEngine engine = GraalJSScriptEngine.create(null,
                Context.newBuilder("js")
                        .allowHostAccess(HostAccess.ALL)
                        .allowHostClassLookup(s -> true)
                        .option("js.ecmascript-version", "2021"));
        File file = ResourceUtils.getFile("classpath:social/socialAPIConfig.mjs");
        engine.eval(new FileReader(file));
        Bindings bindings = engine.getBindings(ScriptContext.ENGINE_SCOPE);
        Map<Object,Object> map = (Map) bindings.get("javaObj");
        for (Map.Entry entry:map.entrySet()){
            System.out.println(entry.getKey());
            System.out.println(entry.getValue());
        }*/

        /*String src = "export const a = 20";

        Context cx = Context.newBuilder("js")
                .allowIO(true)
                .build();
        cx.eval("js", src);*/


        String src = "export const a = 20;console.log(123)";

        Context cx = Context.newBuilder("js")
                .allowIO(true)
                .build();

        cx.eval(Source.newBuilder("js", src, "test.mjs").build());


//        Value array = cx.eval("js", "[1,2,42,4]");
//        cx.eval("js", src).mimeType("application/javascript+module").build();

//        Source source1 =  Source.newBuilder("js", script, "script.mjs").build();
        /*Source source2 =  Source.newBuilder("js", src, "script").mimeType("application/javascript+module").build();
        cx.eval("js", source2.getCharacters());*/
    }
}
